<template>
  <div class="content-main normal">
    <el-menu
      mode="horizontal"
      @select="handleSelect"
      :default-active="activeIndex"
      active-text-color="var(--theme)"
    >
      <el-menu-item index="1">文章</el-menu-item>
      <el-menu-item index="2">分类/标签</el-menu-item>
      <el-menu-item index="3">用户</el-menu-item>
    </el-menu>

    <div class="show-searcg-results">
      <keep-alive>
        <component :is="activeComponent" :list="searchResult"></component>
      </keep-alive>
    </div>
  </div>
</template>

<script>
import API from '~/interface/Search';
export default {
  head() {
    return {
      title: this.pageTitle
    }
  },
  components: {
    Tags: () => import('~/components/search/tags'),
    User: () => import('~/components/search/user'),
    Word: () => import('~/components/search/word')
  },

  data() {
    return {
      keyword: '',
      cachePool: {},
      searchResult: [], // 用作渲染的数据
      activeIndex: '1', // 当前选中的类别
    }
  },

  computed: {
    searchType() {
      const type = this.activeIndex;
      switch (type) {
        case '1':
          return 'getArticle';
        case '2':
          return 'getCategory';
        case '3':
          return 'getUsers';
        default:
          return 'getArticle';
      }
    },
    activeComponent() {
      const index = this.activeIndex;
      switch (index) {
        case '1':
          return 'word';
          break;
        case '2':
          return 'tags';
          break;
        case '3':
          return 'user';
          break;
        default:
          return 'word';
          break;
      }
    },
    pageTitle() {
      return this.keyword + ' 的搜索结果 - [rabbit-pie]'
    }
  },

  created() {
    this.keyword = this.$route.query.keyword
    this.handleSearch('1');
  },

  methods: {
    // 
    /** 切换点击的tabs
     * @param {string} index 点击的tab索引
     * 
     */
    handleSelect(index, indexPath) {
      this.activeIndex = index;
      this.handleSearch();
    },
    handleSearch(index) {
      const method = this.searchType;
      const { keyword, cachePool, activeComponent } = this;

      // 如果请求过这个类型的数据那么不重复请求
      if (cachePool[activeComponent]) {
        this.searchResult = cachePool[activeComponent]
      } else {
        API[method]({ keyword }).then(data => {
          if (data && data.list) {
            this.cachePool[activeComponent] = data.list;
            this.searchResult = data.list;
          }
        });
      }
    }
  }
}
</script>

<style lang="scss" scoped>
</style>